package com.zhongkai.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhongkai.Bean.PageBean;
import com.zhongkai.Bean.SetUnit2;
import com.zhongkai.app.service.AnomalyService;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.PageQuerDao;
import com.zhongkai.jedis.JedisClient;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.Anomaly;
import com.zhongkai.model3.Guard;
import com.zhongkai.model3.SendDate;
import com.zhongkai.model3.SetUnit;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 异常设备列表
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AnomalyServiceImpl implements AnomalyService {


    @Autowired
    private IBaseDao iBaseDao;

    @Autowired
    private PageQuerDao pageQuerDao;

    @Autowired
    private JedisClient jedisClient;
    /**
     * 报警设备列表
     *
     * @param status 状态
     * @param page   当前页数
     * @param rows   每页数据条数
     */
    @Override
    public ZhongkaiResult unit_anomaly_list(String status, Integer page, Integer rows) {
        if (StringUtils.isNullOrEmpty(status) || page == 0 || rows == 0) {

            return ZhongkaiResult.build(400, "参数不完整");
        }

        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(page);
        pageBean.setPageSize(rows);
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Anomaly.class);
        detachedCriteria.add(Restrictions.eq("orders", status)); //增加条件 1 已派单 2未派单
        detachedCriteria.add(Restrictions.eq("solve", "1")); //增加条件 1 未解决 2已解决
        detachedCriteria.addOrder(Order.desc("anoTime")); //根据传入的字段进行降序排序
        pageBean.setDetachedCriteria(detachedCriteria);
        pageQuerDao.pageQuery(pageBean);

        List<Anomaly> anomalies = pageBean.getRows();
        List<SetUnit2> setUnits = new ArrayList<>();
        for (Anomaly anomaly : anomalies) {
            SetUnit2 setUnit2 = new SetUnit2();
            SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.setUuid='" + anomaly.getSetCard() + "'");
            if (setUnit == null){
                continue;
            }else {
                BeanUtils.copyProperties(setUnit,setUnit2); //同属性赋值
                setUnit2.setGet_people(anomaly.getGetPeople());
                setUnit2.setGet_uuid(anomaly.getGetUuid());
                setUnits.add(setUnit2);
                setUnit2 = null;
            }

        }

        pageBean.setRows(setUnits);


/*        List<Anomaly> rows1 = pageBean.getRows();
        ObjectMapper mapper = new ObjectMapper();

        if (rows1 == null){
            return ZhongkaiResult.ok(pageBean);
        }
        for (Anomaly anomaly : rows1) {
            String json = null; //查询缓存
            try {
                json = (String) jedisClient.get(StringStatic.REDIS_UNIT + anomaly.getSetCard());
            } catch (Exception e) {
                e.printStackTrace();
                return ZhongkaiResult.build(500, "redis连接获取失败");
            }

            if (!StringUtils.isNullOrEmpty(json)) {

                try {
                    BigUnitBean  bigUnitBean_json = mapper.readValue(json, BigUnitBean.class);
                    anomaly.setState(bigUnitBean_json.getState());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                anomaly.setState("100");
            }
        }

        pageBean.setRows(rows1);*/

        return ZhongkaiResult.ok(pageBean);

    }


    /**
     * 异常设备派单
     *
     * @param unit_uuid 设备uuid
     * @param send_user 派单人员姓名
     * @param send_uuid 派单人员UUid
     * @param get_name  接单人员姓名
     * @param get_uuid  接单人员UUId
     */
    @Override
    public ZhongkaiResult assign_anomaly(String unit_uuid, String send_user, String send_uuid, String get_name, String get_uuid) {

        if (StringUtils.isNullOrEmpty(unit_uuid) || StringUtils.isNullOrEmpty(get_name) || StringUtils.isNullOrEmpty(get_uuid)) {

            return ZhongkaiResult.build(400, "参数不完整");
        }

        Anomaly anomaly = (Anomaly) iBaseDao.get("from Anomaly an where an.setCard='" + unit_uuid + "'");

        SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.setUuid='" + unit_uuid + "'");

        if (anomaly == null || setUnit == null) {
            return ZhongkaiResult.build(400, "异常设备不存在");
        } else if ("1".equals(anomaly.getOrders())) {
            return ZhongkaiResult.build(400, "此设备已派单");
        } else if ("2".equals(setUnit.getSetRemove())) {
            return ZhongkaiResult.build(400, "此设备已删除");
        }

        anomaly.setOrdPeople(send_user);
        anomaly.setOrdUuid(send_uuid);
        anomaly.setGetPeople(get_name);
        anomaly.setGetUuid(get_uuid);
        anomaly.setSetAlias(setUnit.getSetAlias()); //设备别名
        anomaly.setLatitude(setUnit.getLatitude());
        anomaly.setLongitude(setUnit.getLongitude());

        long millis = new DateTime().getMillis(); //获取当前系统时间戳

        anomaly.setSendTime(millis); //派单时间

        anomaly.setOrders("1");// 1-->已派单  2-->未派单

        //------------------------------------------

        setUnit.setRepair(2); //是否维修 1否  2维修中

        //------------------------------------------

        SendDate sendDate = new SendDate();

        sendDate.setSendName(send_user);
        sendDate.setSendUuid(send_uuid);
        sendDate.setResolveName(get_name);
        sendDate.setResolveUuid(get_uuid);
        sendDate.setSendTime(millis);//派单时间

        sendDate.setWarCause(anomaly.getWarCause()); //异常原因

        sendDate.setAddress(anomaly.getAddress()); //设备地址

        sendDate.setSolve(1); // 1-->未完成 2-->已完成

        sendDate.setUnitUuid(unit_uuid); //设备uuid

        sendDate.setAnoId(anomaly.getAnoId());


         iBaseDao.update(anomaly);
        iBaseDao.update(setUnit);

        iBaseDao.save(sendDate);
        return ZhongkaiResult.ok();


    }


    /**
     * 撤销维修
     *
     * @param unit_uuid 设备uuid
     */
    @Override
    public ZhongkaiResult annul_anomaly(String unit_uuid) throws Exception {

        if (StringUtils.isNullOrEmpty(unit_uuid)) {

            return ZhongkaiResult.build(400, "参数不完整");
        }

        Anomaly anomaly = (Anomaly) iBaseDao.get("from Anomaly an where an.setCard='" + unit_uuid + "'");

        SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.setUuid='" + unit_uuid + "'");

        if (anomaly == null || setUnit == null) {
            return ZhongkaiResult.build(400, "异常设备不存在");
        }


        if (setUnit.getWarning() == 0) { //设备正常

            SendDate sendDate = (SendDate) iBaseDao.get("from SendDate an where an.anoId='" + anomaly.getAnoId() + "'");

            if (sendDate != null) {
                long millis = new DateTime().getMillis(); //获取当前系统时间戳
                sendDate.setSolve(2);
                sendDate.setResolveTime(millis); //完成时间
            }

            setUnit.setRepair(1); //是否维修 1否  2维修中

            iBaseDao.update(setUnit); //修改设备维修状态
            iBaseDao.update(sendDate); //修改派单记录表
            iBaseDao.delete(anomaly); //删除报警设备
            return ZhongkaiResult.ok();


        } else {//设备异常
            setUnit.setRepair(1); //是否维修 1否  2维修中
            anomaly.setOrders("2");// 1-->已派单  2-->未派单

            iBaseDao.update(setUnit);

            iBaseDao.update(anomaly);
            return ZhongkaiResult.ok();


        }

    }


    /**
     * 维修用户列表
     *
     * @param page 当前页数
     * @param rows 每页数据条数
     */
    @Override
    public ZhongkaiResult as_repair_list(Integer page, Integer rows) throws Exception{

        if (page == 0 || rows == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(page);
        pageBean.setPageSize(rows);

        Collection collection = new ArrayList();

        ((ArrayList) collection).add("1");
        ((ArrayList) collection).add("2");
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Guard.class);
        detachedCriteria.add(Restrictions.eq("guaRemove", "1")); //增加条件
        detachedCriteria.add(Restrictions.in("guaState", collection)); //增加条件 1和2 在职和请假的的维修部门员工

        pageBean.setDetachedCriteria(detachedCriteria);
        pageQuerDao.pageQuery(pageBean);
        return ZhongkaiResult.ok(pageBean);


    }

}
